package com.mg.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.dto.PowerAccountDto;
import com.mg.dto.SimpleResult;
import com.mg.mapper.PowerAccountMapper;
import com.mg.model.PowerAccount;
import com.mg.service.PowerAccountService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by mg1213 on 2018/3/18.
 */
@Service
public class PowerAccountServiceImpl implements PowerAccountService {
    @Autowired
    private PowerAccountMapper powerAccountMapper;

    private Logger logger = LogManager.getLogger(PowerAccountServiceImpl.class.getName());

    @Override
    public PageInfo<PowerAccountDto> selectPageInfo(PowerAccountDto powerAccountDto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        List<PowerAccountDto> resultList = powerAccountMapper.selectPageInfo(powerAccountDto);
        PageInfo<PowerAccountDto> result = new PageInfo<>(resultList);
        return result;
    }

    @Override
    public SimpleResult insertPowerAccount(PowerAccount record) {
        SimpleResult result = new SimpleResult();
        try {
            record.setCreateTime(new Date());
            powerAccountMapper.insertSelective(record);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("新增用户算力信息失败 系统未知异常");
            logger.error("新增用户算力信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updatePowerAccount(PowerAccount record) {
        SimpleResult result = new SimpleResult();
        try {
            PowerAccount record1 = new PowerAccount();
            record1.setId(record.getId());
            record1 = powerAccountMapper.selectOne(record1);
            if (record1 == null) {
                result.setSuccess(false);
                result.setMsg("该用户算力信息不存在，请刷新重试！");
            } else {

                powerAccountMapper.updateByPrimaryKeySelective(record);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("更新用户算力信息失败 系统未知异常");
            logger.error("更新用户算力信息失败 系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult deletePowerAccount(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {

                powerAccountMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("删除用户算力信息失败 系统未知异常");
            logger.error("删除用户算力信息失败 系统未知异常", e);
        }
        return result;
    }
}
